const util = require('../../util.js')
const app = getApp()

Page({
  data: {
    saveLogToStorage: false,
    cloudEnv: '',
    miniSDKVersion: '',
    SDKVersion: '',
    enableAllFeatures: false,
    logLevelItems: [
      { name: 'Log Level: none', value: 0 },
      { name: 'Log Level: error', value: 1 },
      { name: 'Log Level: warn', value: 2 },
      { name: 'Log Level: log', value: 3 }
    ]
  },

  onLoad() {
    this.setData({
      miniSDKVersion: app.globalData.perfectLib._getVersion(),
      SDKVersion: my.SDKVersion,
      saveLogToStorage: app.globalData.logger.isEnableSaveLogToStorage(),
      showLogEntry: app.globalData.debugSetting.showLogEntry,
      cloudEnv: app.globalData.debugSetting.cloudEnv,
      enableAllFeatures: app.globalData.featureSetting.enableAllFeatures
    })

    const logLevel = app.globalData.logger.getLogLevel()
    this.setData({
      logLevelItems: [
        { name: 'Log Level: None', value: 0, checked: 0 == logLevel },
        { name: 'Log Level: Error', value: 1, checked: 1 == logLevel },
        { name: 'Log Level: Warn', value: 2, checked: 2 == logLevel },
        { name: 'Log Level: Log', value: 3, checked: 3 == logLevel }
      ]
    })

    const self = this
    my.getRunScene({
      success(result) {
        self.setData({ runScene: result.envVersion })
      }
    })

    const version = require('../../version.js')
    this.setData({ appTag: version.tag })
  },

  onLogLevelChange: function(e) {
    app.globalData.logger.setLogLevel(e.detail.value)
    if (e.detail.value == 0) {
      app.globalData.logger.clearLogHistory()
    }
  },

  onSaveLogToSoorageChanged(e) {
    this.setData({
      saveLogToStorage: e.detail.value
    })

    app.globalData.logger.enableSaveLogToStorage(e.detail.value)
  },

  onEnableAllFeaturesChanged(e) {
    this.setData({
      enableAllFeatures: e.detail.value
    })
    app.globalData.featureSetting.enableAllFeatures = e.detail.value
  },

  onShowLogEntryChanged(e) {
    this.setData({
      showLogEntry: e.detail.value
    })
    app.globalData.debugSetting.showLogEntry = e.detail.value
  },

  onTapCloudEnv(e) {
    const items = ['test', 'online']
    my.showActionSheet({
      items: items,
      success: result => {
        if (result.index === -1) return

        this.updateCloudEnv(items[result.index])
        my.alert({ content: 'You have to restart app!' })
      }
    })
  },

  updateCloudEnv(env) {
    app.globalData.debugSetting.cloudEnv = env
    util.setDebugSetting(app.globalData.debugSetting)
    this.setData({
      cloudEnv: app.globalData.debugSetting.cloudEnv
    })
  },

  async onDownloadModel() {
    let buf1, buf2
    my.showLoading({
      content: 'Run download models benchmark'
    })
    const fileId = 'cloud://4CEE898F88D036014A2D820DC7747676/pfMkModels/200507/iOS/facert_model_0417.mnn.part1.png'
    const cdnUrl = 'https://app-master.youcamapi.cn/miniprogram/MT-Makeup/Taobao/iOS/facert_model_0417.mnn/facert_model_0417.mnn.part1.png'
    const cloudFileStart = Date.now()
    buf1 = await this.download(fileId)
    const myDownloadStart = Date.now()
    buf2 = await this.downloadByUrl(cdnUrl)
    const testingEnd = Date.now()
    const modelSize = (buf2.length / 1024).toFixed(1) + 'KB'
    my.hideLoading()
    my.alert({
      content: 'equal:' + this.equal(buf1, buf2) + '\nmodelSize:' + modelSize + '\ncloudFile:' + (myDownloadStart - cloudFileStart) + '\nmy.download:' + (testingEnd - myDownloadStart)
    })
  },

  async download(fileId) {
    return app.cloud.file.downloadByFileId({ fileId }).then(
      data =>
        new Promise((reslove, reject) => {
          const fileSys = my.getFileSystemManager()
          fileSys.readFile({
            filePath: data[0],
            success: file => reslove(new Uint8Array(file.data).slice(54)),
            fail: error => reject(error)
          })
        })
    )
  },

  async downloadByUrl(url) {
    return my.downloadFile({ url }).then(
      data =>
        new Promise((reslove, reject) => {
          const fileSys = my.getFileSystemManager()
          fileSys.readFile({
            filePath: data.apFilePath,
            success: file => reslove(new Uint8Array(file.data).slice(54)),
            fail: error => reject(error)
          })
        })
    )
  },

  equal(buf1, buf2) {
    if (buf1.length != buf2.length) return false
    let dv1 = new Int8Array(buf1)
    let dv2 = new Int8Array(buf2)
    for (let i = 0; i != buf1.length; i++) {
      if (dv1[i] != dv2[i]) return false
    }
    return true
  },

  onRemoveCache() {
    my.clearStorageSync()
  }
})
